package com.qrpay.util.impl;

import com.qrpay.util.SendService;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 默认网络传输服务实现
 */
public final class DefaultSendServiceImpl implements SendService {

    private RequestConfig requestConfig;

    @Override
    public void setTimeOut(int connectTimeout, int socketTimeout) {
        requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
    }

    @Override
    public String sendPost(String url, String content) throws IOException {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        post.setEntity(new StringEntity(content, Charset.defaultCharset()));

        post.setConfig(requestConfig);

        HttpResponse result = HttpClients.createDefault().execute(post);
        String response = EntityUtils.toString(result.getEntity());
        return response;
    }
}
